package com.xushu.service;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @author 徐庶
 */
@Component
public class UserService   {
	@Autowired
	JdbcTemplate jdbcTemplate;
	@Autowired
	UserService userService;

	@Transactional(readOnly = true)
	public void add() throws TimeoutException {

		jdbcTemplate.execute("UPDATE `test`.`user` SET `age` = 22, " +
				"`name` = 'xushu', `city` = 'BeiJin'  " +
				" WHERE `id` = 164;");

		System.out.println("更新成功!!");
		//((UserService)AopContext.currentProxy()).query();
	}

	//@Transactional(propagation = Propagation.NEVER)
	@Transactional(readOnly = true)
	public void query(){
		List<Map<String, Object>> list = jdbcTemplate.queryForList("SELECT * FROM user");
		System.out.println(list);
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		}
	}




	@Transactional
	public void mainThread(){

		jdbcTemplate.execute("INSERT INTO " +
				"`test`.`user` ( `age`, `name`, `city`) " +
				" VALUES (20, 'xushu', 'BeiJin')");

		Thread thread = new Thread(() -> {
			userService.childThread();
		});
		thread.start();
		try {
			thread.join();
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		}
	}


	@Transactional
	public void childThread(){
		jdbcTemplate.execute("INSERT INTO " +
				"`test`.`user` ( `age`, `name`, `city`) " +
				" VALUES (22, 'zhuge', 'Changsha')");

		throw  new RuntimeException("出错~~");
	}

}